package com.just.springbootmessage.rabbitmq;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.just.springbootmessage.rabbitmq.RabbitContent.QUEUE_FANOUT_A;
import static com.just.springbootmessage.rabbitmq.RabbitContent.QUEUE_FANOUT_B;
import static com.just.springbootmessage.rabbitmq.RabbitContent.QUEUE_FANOUT_C;

@Component
public class RabbitMessageReceiver {
    private static final Logger logger=LoggerFactory.getLogger(RabbitMessageReceiver.class);
    @RabbitListener(queues = RabbitContent.RABBIT_QUEUE1)
    public void receiveMessage(String message){
        logger.info("receive message1:"+message);
    }
    @RabbitListener(queues = RabbitContent.RABBIT_QUEUE2)
    @RabbitHandler
    public void receiveUser(User user){
        logger.info("从rabbitQueue2中收到的User:"+user.toString());
    }

    /**
     * 监听来自topic交换机分发的消息
     */
    @RabbitListener(queues = RabbitContent.TOPIC_QUEUE_MESSAGE)
    public void receiveTopic1(String message){
        logger.info("从"+RabbitContent.TOPIC_QUEUE_MESSAGE+"接收到的消息："+message);
    }
    @RabbitListener(queues = RabbitContent.TOPIC_QUEUE_MESSAGES)
    public void receiveTopic2(String message){
        logger.info("从"+RabbitContent.TOPIC_QUEUE_MESSAGES+"接收到的消息："+message);
    }

    /**
     * 监听fanout交换机的消息
     */
    @RabbitListener(queues = QUEUE_FANOUT_A)
    public void receiveFanoutA(String message){
        logger.info("监听fanout.A队列收到的消息："+message);
    }
    @RabbitListener(queues = QUEUE_FANOUT_B)
    public void receiveFanoutB(String message){
        logger.info("监听fanout.B队列收到的消息："+message);
    }
    @RabbitListener(queues = QUEUE_FANOUT_C)
    public void receiveFanoutC(String message){
        logger.info("监听fanout.C队列收到的消息："+message);
    }
    @RabbitListener(queues = "queue.ack")
    public void receiveAck(Message message,Channel channel) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        logger.info("有应答模式的消息："+new String(message.getBody()));
    }
}
